package com.android.fastride;

import android.app.Activity;
import android.app.Application;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.android.fastride.callback.SimpleActivityLifecycleCallbacks;
import com.android.fastride.manager.DeviceManager;
import com.android.fastride.manager.UserManager;
import com.android.fastride.model.db.GreenDaoManager;
import com.android.fastride.model.http.HttpApiClient;
import com.android.fastride.model.http.service.ControlSysService;
import com.android.fastride.model.sharedpreference.SPreferBase;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.facebook.stetho.Stetho;
import com.peng.lib.crash.CustomActivityOnCrash;
import com.peng.library.mantis.Mantis;
import com.peng.library.mantis.expand.list.link.ListConfig;
import com.peng.library.mantis.expand.refresh.link.OnCreateHeaderViewListener;
import com.peng.library.mantis.expand.refresh.link.RefreshConfig;
import com.peng.library.mantis.hint.HintConfig;
import com.peng.library.mantis.hint.OnShowErrorViewListener;
import com.peng.library.mantis.kit.Kits;
import com.peng.refresh.layout.PtrFrameLayout;
import com.peng.refresh.layout.header.StoreHouseHeader;

import java.util.Stack;

/**
 * Created by admin on 2018/5/14.
 */

public class FastRideApplication extends Application {
    private static final String TAG = "FastRideApplication";
    private static FastRideApplication instance;

    private static String BASE_URL = "http://139.224.221.134:8081/"; // 服务器地址
    private ControlSysService controlSysService;

    //Activity栈
    private Stack<Activity> activityStack = new Stack<>();

    private boolean isDebug;

    public static FastRideApplication getApp() {
        return instance;
    }

    /**
     * 返回网络请求服务
     *
     * @return
     */
    public ControlSysService getControlSysService() {
        return controlSysService;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        CustomActivityOnCrash.install(this);
        UserManager.getInstance().init(this);
        if (BuildConfig.APPLICATION_ID.equals(Kits.Process.getProcessName(this))) {
            initMainProcess();
            Stetho.initializeWithDefaults(this);
            //初始化推送服务
            String deviceId = SPreferBase.getInstance().getString(SPreferBase.BENGUO_CONF_DEVID,
                    null);
            if (!TextUtils.isEmpty(deviceId)) {
//                initPushService();
            }
        }
    }

    /**
     * 主进程初始化
     */
    private void initMainProcess() {
        initMantisUi();
        initGreenDao();
        initHttp();
        initActivityStack();
//        initBaiduMapSdk();
//        LeakCanary.install(this);
    }

    private void initActivityStack() {
        registerActivityLifecycleCallbacks(new SimpleActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                activityStack.add(activity);
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                activityStack.remove(activity);
            }
        });
    }

    /**
     * 获取当前进程最上面的Activity
     *
     * @return
     */
    public Activity getTopActivity() {
        return activityStack.peek();
    }

    /**
     * 返回activity栈的拷贝
     *
     * @return
     */
    public Stack<Activity> getActivityStack() {
        return (Stack<Activity>) activityStack.clone();
    }

    /**
     * 销毁所有的Activity
     */
    public void finishAllActivity() {
        for (Activity activity : activityStack) {
            activity.finish();
        }
    }

    /**
     * 初始化GreenDao
     */
    private void initGreenDao() {
        GreenDaoManager.getInstance().init(this);
    }

    private void initHttp() {
        controlSysService = HttpApiClient.createApiService(
                BASE_URL,
                ControlSysService.class);
    }

    private void initMantisUi() {
        // 必须调用初始化
        Mantis.getInstance().init(this);
        // 设置提示的Builder
        Mantis.getInstance().setHintConfigBuilder(getDefaultConfigBuilder());
        // 设置刷新的Builder
        Mantis.getInstance().setListConfigBuilder(getDefaultListBuilder());
        // 设置列表的Builder
        Mantis.getInstance().setRefreshConfigBuilder(getDefaultRefreshBuilder());
    }

    /**
     * 获取默认提示Builder
     *
     * @return
     */
    public HintConfig.Builder getDefaultConfigBuilder() {
        HintConfig.Builder builder = new HintConfig.Builder();
        builder.layoutEmptyId(R.layout.hint_empty)
                .layoutProgressId(R.layout.hint_progress)
                .layoutErrorId(R.layout.hint_error)
                .showErrorViewListener(
                        new OnShowErrorViewListener() {
                            @Override
                            public void onShow(View errorView, String title, String content) {
                                ((TextView) errorView.findViewById(R.id.tv_error_title)).setText
                                        (title);
                                ((TextView) errorView.findViewById(R.id.tv_error_content))
                                        .setText(content);
                            }
                        })
                .layoutNetworkErrorId(R.layout.hint_net_error);
        return builder;
    }

    /**
     * 获取默认的列表Builder
     *
     * @return
     */
    public ListConfig.Builder getDefaultListBuilder() {
        ListConfig.Builder builder = new ListConfig.Builder();
        builder.canLoadMore(false).loadMoreView(new SimpleLoadMoreView());
        return builder;
    }

    /**
     * 创建刷新的Buidler
     *
     * @return
     */
    public RefreshConfig.Builder getDefaultRefreshBuilder() {
        RefreshConfig.Builder builder = new RefreshConfig.Builder();
        builder.onCreateHeaderViewListener(new OnCreateHeaderViewListener() {
            @Override
            public View onCreateHeaderView(PtrFrameLayout ptrFrameLayout) {
                StoreHouseHeader header = new StoreHouseHeader(FastRideApplication.this);
                int padding = ((int) Kits.Dimens.dpToPx(FastRideApplication.this, 20));
                header.setPadding(0, padding, 0, padding);
                header.initWithString("LOADING.....");
                header.setTextColor(Color.rgb(9, 101, 205));
                return header;
            }
        }).headerBackgroundColor(Color.WHITE);
        return builder;
    }

    /**
     * 获取设备号
     *
     * @return
     */
    public String getDeviceId() {
        String deviceId = SPreferBase.getInstance().getString(SPreferBase.BENGUO_CONF_DEVID, null);
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = DeviceManager.getInstance().getDeviceId(this);
            SPreferBase.getInstance().setStringKey(SPreferBase.BENGUO_CONF_DEVID, deviceId);
        }
        return deviceId;
    }

    /**
     * 清空用户信息
     */
    public void clearUserInfo () {
        UserManager.getInstance().clearUserInfo(this);
    }

    public boolean isDebug() {
        return isDebug;
    }
}
